<?php

class AdminController extends Zend_Controller_Action
{
    const UPLOAD_IMAGE_WIDTH = 300;
    const UPLOAD_IMAGE_HEIGHT = 300;

    /**
     * FlashMessenger
     *
     * @var Lib_Flash
     */
    protected $_flashMessenger = null;

    /**
     * Текущая локаль.
     * @var string
     */
    protected $_locale;

    const SALT = '2SDF897SAm@32!23';

    public function init()
    {
        if ($this->_request->isXmlHttpRequest()) {
            $this->_helper->layout()->disableLayout();
        } else {
            $this->_helper->layout()->setLayout('admin-layout');
        }
        $this->_flashMessenger = new Lib_Flash();
    }


    public function indexAction()
    {

    }

    function __call($method, $args)
    {
        $this->_forward('index');
    }

    function emailAction()
    {
        $paramsManager = new \Managers\Params();
        $params = $paramsManager->getParams();
        if ($this->_request->isPost()) {
            $email = $this->_request->getParam('email');
            $validator = new Zend_Validate_EmailAddress();
            if ($validator->isValid($email)) {
                $paramsManager->setParams($email);
                $this->_flashMessenger->addMessage("You have successfully changed admin's email.",
                                                   Lib_Flash::NOTICE,
                                                   Lib_Flash::PRE);
                $this->_redirect('/admin');

            } else {
                $this->_flashMessenger->addMessage('Invalid email format.',
                                                   Lib_Flash::ERROR,
                                                   Lib_Flash::POST);
            }
        }

        $this->view->params = $params;
    }

    public function filesAction()
    {
        $this->_helper->layout()->disableLayout();
        $result_dir = '/upload/';

        $upload = $_FILES['upload'];
        $upload_dir = dirname(APPLICATION_PATH) . '/public' . $result_dir;
        if (!is_writable($upload_dir)) {
            die("$upload_dir is not writable.");
        }

        $name = '';
        if (move_uploaded_file($upload['tmp_name'], $upload_dir . $upload['name'])) {
            $name = $result_dir . $upload['name'];
            if (preg_match('/image/', $upload['type'])) {
                try {
                    \Managers\Users::resize($upload_dir . $upload['name'], self::UPLOAD_IMAGE_WIDTH, self::UPLOAD_IMAGE_HEIGHT);
                } catch (Exception $e) {
                    die($e->getMessage());
                }
            }
        }
        $this->view->name = $name;
    }


}
